import { createSlice } from '@reduxjs/toolkit'
import { Toast } from 'antd-mobile'
import axios from 'axios'

const billStore = createSlice({
  name: "bill",
  initialState: {
    billList: []
  },
  reducers: {
    setBillList(state, action) {
      state.billList = action.payload
    },
    addBill(state, action) {
      state.billList = [
        action.payload,
        ...state.billList
      ]
    }
  }
})

// 解构action
const { setBillList, addBill } = billStore.actions
// 异步请求, 不理解为什么要函数返回函数？
// 答：方便传参
const getBillList = () => {
  return async (dispatch) => {
    const res = await axios.get('http://localhost:8888/ka')
    console.log(res)
    dispatch(setBillList(res.data))
  }
}

const addBillList = (bill) => {
  return async (dispatch) => {
    await axios.post('http://localhost:8888/ka', bill)
    dispatch(addBill(bill))
    Toast.show({
      content: '添加成功！',
      icon: 'success'
    })
  }
}
// 导出reducer, 主store来组合
const reducer = billStore.reducer
export { getBillList, addBillList }
export default reducer